﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Permissions;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using HslCommunication;
using HslCommunication.ModBus;
using HslCommunication.Profinet.Inovance;
using Microsoft.Win32;

namespace PlasmaMes.Services
{
    public class Modbus
    {
        private static Modbus instance;

        private static readonly object locker = new object();
        private Modbus() { }


        public static Modbus Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (locker)
                    {
                        instance = new Modbus();
                    }
                }
                return instance;
            }
        }


        public ModbusTcpNet modustcp ;
        public volatile bool isModbusConnect = false;


        public bool ConnectModbus(string ip)
        {
            if(isModbusConnect)
            {
                MessageBox.Show("已存在连接，请勿重复连接");
                return false;
            }
            else
            {
                if(modustcp == null)
                    modustcp = new ModbusTcpNet(ip, 502);

                try
                {
                    OperateResult result = modustcp.ConnectServer();
                    if (result.IsSuccess)
                    {
                        LogService.Instance.LogInfo("modbusTcp连接成功");

                        isModbusConnect = true;
                        return true;

                    }
                    else
                    {
                        MessageBox.Show("modbusTcp连接失败，请检查，请手动连接");
                        isModbusConnect = false;
                        return false;
                    }



                }
                catch (Exception ex)
                {
                    MessageBox.Show($"{ex}");
                    LogService.Instance.LogError("modbusTcp连接失败，请检查");
                    return false;
                }
            }
        }


        public bool DisConnectMudbus()
        {
            if(modustcp != null)
            {
                modustcp.ConnectClose();
                modustcp = null;

                LogService.Instance.LogInfo("ModbusTcp 断开成功");

                return true;
            }
            else
            {
                LogService.Instance.LogWarning("请先建立ModbusTcp连接");
                return false;
            }

           
        }

        public bool WriteOneRegister_Short(string addr, short value, bool islog = true)
        {
            if(isModbusConnect)
            {
                OperateResult operateResult = modustcp.WriteOneRegister(addr, value);
                if (operateResult.IsSuccess)
                {
                    if(islog)
                        LogService.Instance.LogInfo($"modbusTcp写寄存器{addr}, 值：{value} 成功");
                   
                    return true;
                }
                else
                {
                    if(islog)
                        LogService.Instance.LogInfo($"modbusTcp写寄存器{addr}, 值：{value} 失败");

                    return false;
                }

            }
            else
            {
                LogService.Instance.LogError("modbusTcp还没建立连接，请连接");
                return false ;
            }
        }

        public bool WriteRegister_Short(string addr, short value)
        {
            if (isModbusConnect)
            {
               
                byte[] bytes = BitConverter.GetBytes(value);

                ushort reg1 = BitConverter.ToUInt16(bytes, 0); // 低 16 位
                ushort reg2 = BitConverter.ToUInt16(bytes, 2); // 高 16 位

                OperateResult operateResult = modustcp.WriteOneRegister(addr, reg1);
                if (!operateResult.IsSuccess)
                {
                    LogService.Instance.LogInfo($"写入地址： {addr} 失败");
                    return false;
                }

                int addr2 = int.Parse(addr) + 1;
                operateResult = modustcp.WriteOneRegister(addr2.ToString(), reg2);
                if (!operateResult.IsSuccess)
                {
                    LogService.Instance.LogInfo($"写入地址： {addr} 失败");
                    return false;
                }

                return true;
            }
            else
            {
                LogService.Instance.LogError("modbusTcp还没建立连接，请连接");
                return false;
            }
        }

        public bool WriteRegister_Float(string addr, float value)
        {
            if (isModbusConnect)
            {
              
                // 将 float 转换为字节数组
                byte[] bytes = BitConverter.GetBytes(value);

                // 假设系统是小端序，使用 ToUInt16 方法转换为 ushort
                ushort reg1 = BitConverter.ToUInt16(bytes, 0); // 低 16 位
                ushort reg2 = BitConverter.ToUInt16(bytes, 2); // 高 16 位

                OperateResult operateResult = modustcp.Write(addr, reg1);
                if (operateResult.IsSuccess)
                {
                    int addr2 = int.Parse(addr) + 1;
                    operateResult = modustcp.Write(addr2.ToString(), reg2);
                    if (operateResult.IsSuccess)
                    {
                        LogService.Instance.LogInfo($"modbusTcp写寄存器{addr}, 值：{value} 成功");
                        return true;
                    }
                    else
                    {
                        LogService.Instance.LogInfo($"modbusTcp写寄存器{addr2}, 值：{value} 失败");
                        return false;
                    }
                }
                else
                {
                    LogService.Instance.LogInfo($"modbusTcp写寄存器{addr}, 值：{value} 失败");
                    return false;
                }

            }
            else
            {
                LogService.Instance.LogError("modbusTcp还没建立连接，请连接");
                return false;
            }
        }


        public bool ReadRegister_Int16(string addr, ref int value)
        {
            if (isModbusConnect)
            {
                OperateResult operateResult = modustcp.ReadInt16(addr);
                if(operateResult.IsSuccess)
                {
                    value = modustcp.ReadInt16(addr).Content;
                    return true;
                }
                else
                {
                    LogService.Instance.LogError($"modbusTcp读取寄存器：{addr} 失败");
                    return false;
                }
            }
            else
            {
                LogService.Instance.LogError("modbusTcp还没建立连接，请连接");
                return false;
            }

        }

        public bool ReadRegister_Float(string addr, ref float value)
        {
            if (isModbusConnect)
            {
                OperateResult operateResult = modustcp.ReadFloat(addr);
                if (operateResult.IsSuccess)
                {
                    value = modustcp.ReadFloat(addr).Content;
                    return true;
                }
                else
                {
                    LogService.Instance.LogError($"读取寄存器：{addr} 失败");
                    return false;
                }
            }
            else
            {
                LogService.Instance.LogError("modbusTcp还没建立连接，请连接");
                return false;
            }

        }


       

    }


}
